package com.wtgroup.demo.leetcode.q003_重复字符的最长子串;

import java.util.HashSet;
import java.util.Set;

/**
 * @author dafei
 * @version 0.1
 * @date 2021/3/16 11:19
 */
public class Solution1 {
    /*
    官方解法之一.
    虽然可能会有很多无用循环(指针没有跳跃), 但快很多.
    */

    public static void main(String[] args) {
        String[] ss = {"", " ", "abcabcbb", "bbbbb", "pwwkew", "au"};
        for (String s : ss) {
            int res = new Solution1().lengthOfLongestSubstring(s);
            System.out.println(res);
        }
    }

    // set 判重, 不跳跃
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> occ = new HashSet<Character>();
        int rk = -1, ans = 0;
        for (int i = 0; i < n; i++) {
            if (i!=0) {
                occ.remove(s.charAt(i - 1));
            }
            while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
                occ.add(s.charAt(rk + 1));
                ++rk;
            }
            ans = Math.max(ans, rk - i + 1);
        }
        return ans;
    }

}
